package com.njupt.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/11/24 14:02
 * @Description: 590. N 叉树的后序遍历
 * @Version: 1.0
 */


public class Npostorder {



    public void NOrder(Node root,List<Integer> results){

        if(root == null) return;
        if(root.children != null){
            for (int i = 0; i < root.children.size(); i++) {
                NOrder(root.children.get(i),results);
                results.add(root.children.get(i).val);
            }
        }
    }

    public List<Integer> postorder(Node root) {
        List<Integer> results = new ArrayList<>();
        NOrder(root,results);
        if(root != null){
            results.add(root.val);
        }

        return results;
    }

    public static void main(String[] args) {
        Node root = new Node(1);
        Node node3 = new Node(3);
        Node node2 = new Node(2);
        Node node4 = new Node(4);
        List<Node> nodes1 = new ArrayList<>();
        nodes1.add(node3); nodes1.add(node2); nodes1.add(node4);
        root.children = nodes1;

        Node node5 = new Node(5);
        Node node6 = new Node(6);
        List<Node> nodes3 = new ArrayList<>();
        nodes3.add(node5);
        nodes3.add(node6);
        node3.children = nodes3;

        Npostorder test = new Npostorder();
        List<Integer> postorder = test.postorder(root);
        System.out.println(postorder);
    }
}
